// elder/update/update.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    updateList:[],
    page:1,
    userId:'',
    active:0,
    identity:'',
    show:false,
    my_comment:'',
    //预览图片是哪一条动态的
    index1:'',
    index:'',
    like:'/static/点赞yes.png',
    dislike:'/static/点赞no.png',
    //打开的是哪个评论区
    commentContent:[],
    user_nickName:"forever",
		user_headPicture:"/static/headPicture-1.jpg",
		user_background:"https://img0.baidu.com/it/u=1252257814,349166994&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800",
  },
  //取消评论
  delete_comment(e){
   
    var commentContent = this.data.commentContent
    var updateList = this.data.updateList
    var index = e.currentTarget.dataset.index
    console.log(index)
    var id = commentContent[index].id
    wx.request({
      url: `https://zhixiao.site:8080/dynamic/deleteComment?id=${id}`,
      method:'DELETE',
      success:(res)=>{
        console.log(res)
        commentContent.splice(index,1)
        // updateList[index].comments = commentContent
        this.setData({
          updateList:updateList,
          commentContent:commentContent
        })
      }
    })

  },

  //点击图片可以预览
  imgClick(e){
    var index = e.currentTarget.dataset.index
    console.log(index)
    var imgUrl = this.data.updateList[this.data.index1].fileList
    console.log(imgUrl)
    wx.previewImage({
      urls: imgUrl,
      current:imgUrl[index],
      success:(res=>{
        console.log(res)
      })
    })
  },
  click1(e){
    var index1 = e.currentTarget.dataset.index
    console.log(index1)
    this.setData({
      index1:index1
    })
  },
  forward(e){
    Toast('暂不支持此功能')
    return
    var index = e.currentTarget.dataset.index
    Dialog.confirm({
      title: '标题',
      message: '确定要转发此动态？',
    })
      .then(() => {
        // on confirm
        // wx.request({
        //   url: 'https://zhixiao.site:8080/dynamic/forward/new',
        //   data:{
        //     userId:wx.getStorageSync('userid'),
        //     dynamicId:this.updateList[index].id,
        //     content:
        //     // content
        //   }
        // })
      })
      .catch(() => {
        // on cancel
      });
  },
  //我的动态
  toMy(){
    wx.navigateTo({
      url: '/elder/update_my/update_my',
    })
  },

  onClose() {
    this.setData({ show: false });
  },
  //打开评论区
  showPopup(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      index:index
    })
    console.log(index)
    const updateList = this.data.updateList
    this.setData({ 
      show: true,
      commentContent:updateList[index].comments
     });
  },
  //点赞
  like(e){
    var index = e.currentTarget.dataset.index
    const updateList = this.data.updateList
    // updatesList[index].likeStatus = updatesList[index].likeStatus? false : true
    updateList[index].likes = parseInt(updateList[index].likes) + 1
    wx.request({
      url: 'https://zhixiao.site:8080/dynamic/like',
      data:{
        userId:wx.getStorageSync('userid'),
        dynamicId:updateList[index].id,
      },
      success:(res)=>{
        console.log(res)
        updateList[index].likeFlag = res.data.data.id
        this.setData({
          updateList:updateList,
        })
      }
    })
   
  },
  //取消点赞
  dislike(e){
    var index = e.currentTarget.dataset.index
    console.log(index)
    const updateList = this.data.updateList
    updateList[index].likes = parseInt(updateList[index].likes) - 1
    wx.request({
      url: `https://zhixiao.site:8080/dynamic/cancelLike?id=${updateList[index].likeFlag}`,
      method:'DELETE',
      success:(res)=>{
        console.log(res)
      }
    })
    updateList[index].likeFlag = -1
    this.setData({
      updateList:updateList,
    })
  },
  //发表动态
  publish(){
    wx.navigateTo({
      url: '/elder/publish/publish',
    })
  },
  onChange(event) {
    // event.detail 的值为当前选中项的索引
    this.setData({ active: event.detail });
  },

  
  bindinput(e){
    this.setData({
      my_comment:e.detail.value
    })
  },
  //发表评论
  confirm(){
    var index = this.data.index
    var updateList = this.data.updateList
    var commentContent = this.data.commentContent
    wx.request({
      url: 'https://zhixiao.site:8080/dynamic/comment',
      method:'POST',
      data:{
        userId:wx.getStorageSync('userid'),
        dynamicId:updateList[index].id,
        content:this.data.my_comment
      },
      header:{
        'Content-Type':'application/json',
      },
      success:(res)=>{
        console.log(res)
      },
      complete:(res)=>{
        var comment = {}
        comment.name = this.data.elderName
        comment.content = this.data.my_comment
        comment.id = res.data.data.id
        comment.userId = wx.getStorageSync('userid')
        updateList[index].comments.push(comment)
        this.setData({
          updateList:updateList,
          commentContent:commentContent
        })
      }
    })
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    this.queryMsg()
    this.queryUpdates()

    this.setData({
      active:options.active,
      userId:wx.getStorageSync('userid')
    })
  },
  //老人个人信息查询
  queryMsg(){
    wx.request({
      url: `https://zhixiao.site:8080/client/elder/info?userId=${wx.getStorageSync('userid')}`,
      success:(res)=>{
        
        this.setData({
          elderName:res.data.data.nickname
        })
      }
      
    })
  },
  queryUpdates(){
    wx.request({
      url: 'https://zhixiao.site:8080/dynamic/query',
      data:{
        careHomeName:wx.getStorageSync('beadhouse'),
        page:this.data.page,
        pageSize:5,
        userId:wx.getStorageSync('userid')
      },
      success:(res)=>{
        console.log("获取到的分页数据")
        console.log(res)
        var updateList = res.data.data
        for(var i in updateList){
          let fileList = updateList[i].imageUrl.split(";")
          updateList[i].fileList = this.storageImage(fileList)
          console.log(fileList)
        }
        this.setData({
          updateList:[...this.data.updateList,...updateList]
        })
      },
      complete:(res)=>{
        var updateList = this.data.updateList
        updateList.sort((a, b) => a.createTime - b.createTime)
        this.setData({
          updateList:updateList
        })
      }
    })
  },
 
  storageImage(fileList) {
    for (let i = 0; i < fileList.length; i++) {
      ((index) => {
        let url = fileList[index];
        if (wx.getStorageSync(url) !== '') {
          fileList[index] = wx.getStorageSync(url);
        } else {
          wx.downloadFile({
            url: url,
            success: function (res) {
              if (res.statusCode === 200) {
                console.log(url);
                console.log(res.tempFilePath);
                fileList[index] = res.tempFilePath;
                wx.setStorageSync(url, res.tempFilePath);
              } else {
                console.log('图片下载失败');
              }
            },
            fail: function (res) {
              console.log(res);
              console.log('图片下载失败');
            }
          });
        }
      })(i);
    }
    return fileList;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
    wx.hideHomeButton()
    var isUpdate = wx.getStorageSync('update')
    if(isUpdate===1){
      this.setData({
        updateList:[],
        page:1
      })
      this.queryUpdates()
      wx.setStorageSync('update', 0)
    }
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      page:this.data.page + 1
    })
    this.queryUpdates()
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})